package com.atguigu.demojuc.chap02;

import java.util.concurrent.locks.ReentrantLock;

//资源类
class Ticket {
    private int ticket = 20; //票数

    //private ReentrantLock lock = new ReentrantLock(); //非公平锁   Sync sync = new NonfairSync();
    //公平锁是以牺牲系统性能为代价的。
    ReentrantLock lock = new ReentrantLock(true);
    public void sale(){
        lock.lock();
        try {
            if (ticket > 0){
                System.out.println(Thread.currentThread().getName() + "\t" + "售卖了第"+ticket+"张票");
                ticket--;
                check();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void check(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t" + "还剩余"+ticket+"张票");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

/**
 * 例子：卖票程序
 * <p>
 * 多线程编程模板：
 * 上：
 * 高内聚 低耦合
 * 线程 操作 资源类
 */
public class SaleTicket {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        }, "C").start();
    }
}
